package com.zbkj.crmeb.supplier.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.PageParamRequest;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageHelper;
import com.zbkj.crmeb.chant.request.EnableTakeAddressRequest;
import com.zbkj.crmeb.supplier.dao.SupplierAddressDao;
import com.zbkj.crmeb.supplier.model.SupplierAddress;
import com.zbkj.crmeb.supplier.request.SupplierAddressRequest;
import com.zbkj.crmeb.supplier.request.SupplierSaveAddressRequest;
import com.zbkj.crmeb.supplier.service.SupplierAddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cdm
 * @since 2023-08-28
 */
@Service
public class SupplierAddressServiceImpl extends ServiceImpl<SupplierAddressDao, SupplierAddress> implements SupplierAddressService {


    @Override
    public CommonResult<String> saveOrUpdateAddress(SupplierSaveAddressRequest request) {
        SupplierAddress supplierAddress = new SupplierAddress();
        BeanUtils.copyProperties(request, supplierAddress);
        //状态启用
        return saveOrUpdate(supplierAddress) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public CommonResult<String> deleteTakeAddress(Integer id) {
        checkAddressExist(id);
        return removeById(id) ? CommonResult.success() : CommonResult.failed();
    }

    @Override
    public List<SupplierAddress> addressList(SupplierAddressRequest request) {
        PageHelper.startPage(request.getPage(), request.getLimit());
        LambdaQueryWrapper queryWrapper = Wrappers.<SupplierAddress>lambdaQuery()
                .eq(null != request.getSupplierId(), SupplierAddress::getSupplierId, request.getSupplierId());
        return list(queryWrapper);
    }

    @Override
    public CommonResult<String> enableTakeAddress(EnableTakeAddressRequest request) {
        SupplierAddress supplierAddress = checkAddressExist(request.getId());
        supplierAddress.setStatus(request.getStatus());
        return updateById(supplierAddress) ? CommonResult.success() : CommonResult.failed();
    }


    public SupplierAddress checkAddressExist(Integer id) {
        SupplierAddress merchantAddress = getOne(Wrappers.<SupplierAddress>lambdaQuery().eq(SupplierAddress::getId, id));
        if (null == merchantAddress) {
            throw new CrmebException("该地址不存在");
        }
        return merchantAddress;
    }

}
